<?php

namespace app\sys\api;

class Menu extends Common
{
    public function add()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');
        $Menu = new \app\common\logic\Menu();

        //生成hashid
        $id = get_hashid();
        if ($id === false)
            return $this->error('出现内部错误，请稍后重试');

        $req['id'] = $id;

        $ret = $Menu->addItem($req);
        if ($ret === false)
            return $this->error($Menu->getError());

        return $this->success('添加成功');
    }

    public function update()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');

        if (!isset($req['id']) || empty($req['id']))
            return $this->error('请选择要更新的菜单');

        $id = $req['id'];

        $Menu = new \app\common\logic\Menu();
        $ret = $Menu->updateItem($req, ['id' => $id]);
        if ($ret === false)
            return $this->error($Menu->getError());

        return $this->success('更新成功');
    }

    public function delete()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');

        if (!isset($req['id']) || empty($req['id']))
            return $this->error('请选择要删除的菜单');

        $id = $req['id'];
        $ids = is_array($id) ? $id : [$id];

        //判断是否存在下级菜单
        $del_id = [];
        $error = 0;
        foreach ($ids as $val) {
            $menu = \app\common\logic\Menu::where(['pid' => $val])->find();
            if (!empty($menu)) $error++;
            else $del_id[] = $val;
        }

        if (!empty($del_id)) {
            $ret = \app\common\logic\Menu::where(['id' => ['in', $del_id]])->delete();
            if ($ret === false)
                return $this->error('删除失败，请稍后重试');
        }

        if ($error > 0)
            return $this->error('请先删除子菜单后重试');

        return $this->success('删除成功');
    }

    public function get()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');

        if (!isset($req['id']) || empty($req['id']))
            return $this->error('请选择要查看的菜单');

        $ret = \app\common\logic\Menu::get(['id' => $req['id']]);
        if (empty($ret))
            return $this->error('菜单不存在');

        return $this->success($ret);
    }

    public function lists()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');

        if (!isset($req['pid']) || empty($req['pid'])) $pid = 0;
        else $pid = $req['pid'];

        $where = ['pid' => $pid];

        $ret = \app\common\logic\Menu::getList($where);
        return $this->success($ret);
    }
}